package com.veo.converter;

import com.veo.bean.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class MyMessageConverter implements HttpMessageConverter<User> {
    //是否可读，即读取requestBody中的内容
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    //是否可写，即写出数据
    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        //判断返回值是否为User类型，是这个类型的话就为可读，就可以使用这个转换器
        return aClass.isAssignableFrom(User.class);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        //自定义请求头的数据类型
        return MediaType.parseMediaTypes("application/x-ko");
    }

    @Override
    public User read(Class<? extends User> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(User user, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        //写会数据
        OutputStream out = httpOutputMessage.getBody();
        String data = user.getName()+", "+user.getAge();
        out.write(data.getBytes());
    }
}
